import Vue from 'vue'
import Router from 'vue-router'
import { local } from 'me-view/src/index'
Vue.use(Router)

/**
 * 转换为 '-' 替换驼峰命名
 * @param {String} target 路径
 * @param {String} connector 分隔符 默认 -
 */
function formatFile (target, connector = '-') {
  return target.split('/').flatMap(item => {
    const newItem = item.replace(/([A-Z])/g, $1 => connector + $1.toLowerCase())
    return newItem.startsWith('-') ? newItem.replace('-', '') : newItem
  }).join('/')
}

// 动态获取路由： 根据目录结构

const fileDocument = require.context('../../document/', false, /.md$/).keys()
const filePackage = require.context('../../../packages/', true, /.md$/).keys()
const route = []
function parseRoute (target, callback = () => {}) {
  return [ target ].flat().flatMap(item => {
    item = item.replace('./', '')
    const [ first ] = item.split('/')
    const path = `/document/${formatFile(first.replace(/.md$/, ''))}`
    route.push(path)
    return {
      path,
      component: callback(item)
    }
  })
}
const children = [
  ...parseRoute(fileDocument, item => () => import('me-view/multiple-page/document/' + item)),
  ...parseRoute(filePackage.filter(item => item.includes('README.md')), item => () => import('me-view/packages/' + item))
]

local.set('route-document', route)

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      redirect: '/document/install',
      component: () => import('me-view/multiple-page/layout/Document.vue'),
      children
    }
  ]
})
